package com.douxg.learning.spring;

import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * @Description
 * @Auther douxg
 * @Date 2021/4/22 12:02
 */
public class YAMLPropertySourceFactory implements PropertySourceFactory {

    public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        //创建一个YAML解析工厂。
//        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        YamlMapFactoryBean factory = new YamlMapFactoryBean();
        //设置资源。
        factory.setResources(encodedResource.getResource());

        //获取解析后的Properties对象
        Map<String, Object> object = factory.getObject();
        //返回。此时不能像默认工厂那样返回ResourcePropertySource对象 ，要返回他的父类PropertiesPropertySource对象。
        return name != null ? new MapPropertySource(name, object) :
                new MapPropertySource(encodedResource.getResource().getFilename(), object);
    }
}
